﻿using AuthCenter.Api.Write.Application.Command.RoleMenu;
using AuthCenter.Application;
using AuthCenter.Domain;
using AuthCenter.ErrorCode;
using AutoMapper;
using MediatR;
using System.Transactions;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace AuthCenter.Api.Write.Application.Hander.RoleMenu
{
    public class AddRoleMenuHander:IRequestHandler<AddRoleMenuCommand,ApiResult<int>>
    {
        private readonly IBaseRepository<RoleModel> _roleRepository;
        private readonly IBaseRepository<RoleMenuModel> _roleMenuRepository;
        private readonly IBaseRepository<MenuModel> _menuRepository;
        private readonly IBaseRepository<UserModel> _userRepository;
        private readonly IBaseRepository<UserRoleModel> _userroleRepository;
        private readonly IMapper _mapper;
        public AddRoleMenuHander(IBaseRepository<RoleModel> roleRepository, IBaseRepository<RoleMenuModel> roleMenuRepository, IMapper mapper, IBaseRepository<MenuModel> menuRepository, IBaseRepository<UserModel> userRepository, IBaseRepository<UserRoleModel> userroleRepository)
        {
            _roleRepository = roleRepository;
            _roleMenuRepository = roleMenuRepository;
            _mapper = mapper;
            _menuRepository = menuRepository;
            _userRepository = userRepository;
            _userroleRepository = userroleRepository;
        }
        /// <summary>
        /// 添加角色菜单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(AddRoleMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                var t = new List<RoleMenuModel>();
                foreach (var item in request.MId)
                {
                    t.Add(new RoleMenuModel
                    {
                        MId = item,
                        RId = request.RId
                    });
                }
                int i=_roleMenuRepository.Create(t);
                tran.Complete();
                if (i > 0)
                {
                    res.Code = ApiEnums.OK;
                    res.Message = "添加成功";
                    res.Data = i;
                }
                else 
                {
                    res.Code = ApiEnums.Fail;
                    res.Message = "添加失败";
                }
                return Task.FromResult(res);
            }
        }
    }
}
